import Taro, { Component } from '@tarojs/taro'
import { View, Text, Swiper, SwiperItem, Map, Image, Picker } from '@tarojs/components'
import './index.scss'
import { AtButton, AtFab, AtInput, AtMessage, AtList, AtListItem, AtSearchBar, AtIcon, AtTabs, AtTabsPane, AtInputNumber, AtCard, AtFloatLayout, AtCalendar } from 'taro-ui'
import AtTabBar_index_GL from '../../components/AtTabBar_index_GL';
// 引入SDK核心类
import requets from '../../service/api';

// import PublicTemplate from '../../components/PublicTemplate'
var QQMapWX = require('../../assets/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');

var dingwei = require('../../assets/img/dingwei.png')
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'D43BZ-P7MKO-N4TWG-SGR4H-SLJIE-YAFTN' // 必填
});
var yiyuan_icon = require('../../assets/img/yiyuan_icon.png')
var liang = require('../../assets/img/liang.png')
var shouji = require('../../assets/img/shouji.png')
var cheqian = require('../../assets/img/cheqian.png')
var dai = require('../../assets/img/dai.png')
var riqi = require('../../assets/img/riqi.png')
var lianxi = require('../../assets/img/lianxi.png')
var num = 1
var curDate = new Date();
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份 
    "d+": this.getDate(),                    //日 
    "h+": this.getHours(),                   //小时 
    "m+": this.getMinutes(),                 //分 
    "s+": this.getSeconds(),                 //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds()             //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
export default class Index extends Component {
  config = {
    navigationBarTitleText: '医疗废物管理助手'
  }

  state = {
    isOpened: false,
    end: '',
    start: '',
    flag: false,
    hospitalId: '',
    loading: false,
    shoujihao: '',
    lianxiren: '',
    ListData: [],
    AtListData: [],
    downDragStyle: {
      height: '0vh',
      transition: `all 1s`,
      display: 'none'
    },
    dateSel: '',
    hospitalName: '',

    current: 0,//轮播图index
    data: [

    ],
    tongshu: 0,
    tong: 0,
    qianke: 0,
    rows: 10,
    userId: '',
    dargStyle: {//下拉框的样式
      top: 0 + 'px'
    },
    downDragStyle: {//下拉图标的样式
      height: 0 + 'px'
    },
    downText: '下拉刷新',
    upDragStyle: {//上拉图标样式
      height: 0 + 'px'
    },
    pullText: '上拉加载更多',
    start_p: {},
    scrollY: true,
    dargState: 0//刷新状态 0不做操作 1刷新 -1加载更多
  }

  componentWillMount() { }

  componentDidMount() {
   



    Taro.getStorage({
      key: 'hospitalId',
      success: (res) => {
        this.setState({
          hospitalId: res.data,
          dateSel: new Date(curDate.getTime() + 24*60*60*1000).format("yyyy-MM-dd")
        }, () => {
          this.pagingQueryCollectorRecord()
        })
      }
    })






  }

  onMessagehandleClick = (type, text) => {
    Taro.atMessage({
      'message': text,
      'type': type,
    })
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  handleClick(value) {
    this.setState({
      current: value
    })
  }

  pagingQueryCollectorRecord = () => {

    let params = {
      endTime: this.state.end,
      hospitalId: this.state.hospitalId,
      page: 1,
      rows: this.state.rows,
      startTime: this.state.start,
    }

    requets.baseOptions({
      url: `/zjn-web/zjn/collector/demand/pagingQueryCollectorDemand`,
      method: 'POST',
      data: params
    }).then((res) => {
      if (res.data.rc === 0) {
        if (res.data.ret.items.length > 0) {
          res.data.ret.items.forEach((item) => {
            // item.url = item.auditType == '1' ? shenhe : item.auditType == '2' ? tongyi : jujue
            item.time = new Date(item.expectData).format("yyyy-MM-dd ");
          })
          this.setState({
            ListData: res.data.ret.items,
            count: res.data.ret.count
          })
          if (!res.data.ret.count) {
            this.onMessagehandleClick('', '暂无数据')
          } else {
            if (res.data.ret.count / 10 > 1) {

            } else {
              this.onMessagehandleClick('', '暂无更多数据')
            }
          }

        } else {
          this.setState({
            ListData: res.data.ret.items,
            count: res.data.ret.count
          })
          this.onMessagehandleClick('', '暂无数据')
        }

      }
    })

  }

  reduction() {//还原初始设置
    const time = 0.5;
    this.setState({
      upDragStyle: {//上拉图标样式
        height: 0 + 'px',
        transition: `all ${time}s`
      },
      dargState: 0,
      dargStyle: {
        top: 0 + 'px',
        transition: `all ${time}s`
      },
      downDragStyle: {
        height: 0 + 'px',
        transition: `all ${time}s`
      },
      scrollY: true
    })
    setTimeout(() => {
      this.setState({
        dargStyle: {
          top: 0 + 'px',
        },
        upDragStyle: {//上拉图标样式
          height: 0 + 'px'
        },
        pullText: '上拉加载更多',
        downText: '下拉刷新'
      })
    }, time * 1000);
  }
  touchStart(e) {
    this.setState({
      start_p: e.touches[0]
    })
  }
  touchmove(e) {
    let that = this
    let move_p = e.touches[0],//移动时的位置
      deviationX = 0.30,//左右偏移量(超过这个偏移量不执行下拉操作)
      deviationY = 70,//拉动长度（低于这个值的时候不执行）
      maxY = 100;//拉动的最大高度

    let start_x = this.state.start_p.clientX,
      start_y = this.state.start_p.clientY,
      move_x = move_p.clientX,
      move_y = move_p.clientY;


    //得到偏移数值
    let dev = Math.abs(move_x - start_x) / Math.abs(move_y - start_y);
    if (dev < deviationX) {//当偏移数值大于设置的偏移数值时则不执行操作
      let pY = Math.abs(move_y - start_y) / 3.5;//拖动倍率（使拖动的时候有粘滞的感觉--试了很多次 这个倍率刚好）
      if (move_y - start_y > 0) {//下拉操作
        if (pY >= deviationY) {
          this.setState({ dargState: 1, downText: '释放刷新' })
        } else {
          this.setState({ dargState: 0, downText: '下拉刷新' })
        }
        if (pY >= maxY) {
          pY = maxY
        }
        this.setState({
          dargStyle: {
            top: pY + 'px',
          },
          downDragStyle: {
            height: pY + 'px'
          },
          scrollY: false//拖动的时候禁用
        })
      }
      if (start_y - move_y > 0) {//上拉操作
        console.log('上拉操作')
        if (pY >= deviationY) {
          this.setState({ dargState: -1, pullText: '释放加载更多' })
        } else {
          this.setState({ dargState: 0, pullText: '上拉加载更多' })
        }
        if (pY >= maxY) {
          pY = maxY
        }
        this.setState({
          dargStyle: {
            top: -pY + 'px',
          },
          upDragStyle: {
            height: pY + 'px'
          },
          scrollY: false//拖动的时候禁用
        })
      }

    }
  }
  pull() {//上拉
    console.log('上拉')
    // this.props.onPull()
    console.log('上拉')
    // this.props.onPull()
    let rows = this.state.rows + 10
    this.setState({
      rows
    }, () => {
      this.pagingQueryCollectorRecord()
    })
  }
  down() {//下拉
    console.log('下拉')
    // this.props.onDown()
    let rows = 10
    this.setState({
      rows
    }, () => {
      this.pagingQueryCollectorRecord()
    })
  }
  ScrollToUpper() { //滚动到顶部事件
    console.log('滚动到顶部事件')
    // this.props.Upper()
  }
  ScrollToLower() { //滚动到底部事件
    console.log('滚动到底部事件')
    // this.props.Lower()
  }
  touchEnd(e) {
    if (this.state.dargState === 1) {
      this.down()
    } else if (this.state.dargState === -1) {
      this.pull()
    }
    this.reduction()
  }






  stringToEllipsis = (text, lens) => {
    let textCopy = text;
    let len = lens ? lens : 10;
    text = text ? (text.length > len ? text.substr(0, len - 1) + '...' : text) : '';
    return text
  }


  handleChange_AtInputNumber = (v, val) => {
    this.setState({
      [v]: val
    })
  }

  onDateChange = e => {
    this.setState({
      dateSel: e.detail.value
    })
  }

  handleChangeInput(v, value) {
    this.setState({
      [v]: value
    })

  }

  onSubmit = () => {
    this.setState({
      loading: true
    })

    if (!this.state.lianxiren) {
      this.onMessagehandleClick('warning', '请填写联系人')
    }
    if (!this.state.shoujihao) {
      this.onMessagehandleClick('warning', '请填写联系方式')
    }


    let params = {
      bucketNum: this.state.tong,
      contacts: this.state.lianxiren,
      expectData: this.state.dateSel,
      hospitalId: this.state.hospitalId,
      phone: this.state.shoujihao,
      weight: this.state.qianke,


    }

    requets.baseOptions({
      url: `/zjn-web/zjn/collector/demand/insertCollectorDemand`,
      method: 'POST',
      data: params
    }).then((res) => {
      // console.log(res)
      if (res.data.rc === 0) {
        this.onMessagehandleClick('success', '提交成功')
        this.setState({
          dateSel: new Date().format("yyyy-MM-dd"),
          tong:0,
          lianxiren:'',
          shoujihao:'',
          qianke:0
        })
      } else {
        this.onMessagehandleClick('warning', '提交失败')
      }
      this.setState({
        loading: false
      })

    })
  }

  onSelectDate = (SelectDate) => {
    console.log(SelectDate)
    if (SelectDate.value.end) {
      this.setState({
        end: SelectDate.value.end,
        start: SelectDate.value.start,
        flag: true
      })
    } else {
      this.setState({
        flag: false
      })
    }
  }

  onisOpened = () => {
    console.log(123)
    this.setState({
      isOpened: !this.state.isOpened
    })
  }

  ononClose = () => {
    this.setState({
      isOpened: !this.state.isOpened
    })
  }

  onIndex = (item) => {
    console.log(item)
  }
  render() {
    let dargStyle = this.state.dargStyle;
    let downDragStyle = this.state.downDragStyle;
    let upDragStyle = this.state.upDragStyle;
    const tabList = [{ title: '信息上报' }, { title: '上报历史' }]
    const ListData1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    const { ListData, end, start, isOpened, markers, longitude, latitude, data, current, AtListData, tong, qianke, lianxiren, shoujihao, loading } = this.state
    return (
      <View className='index'>
        <AtTabBar_index_GL current={0} />
        <AtMessage />
        <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
          <AtTabsPane current={this.state.current} index={0} >
            <View className="tab1" >
              <AtCard
                isFull={true}
                title='医废待收集情况'
                thumb={dai}
              >
                <View className="AtInputNumber">
                  <View>
                    桶数:<AtInputNumber
                      min={0}
                      max={999}
                      step={1}
                      value={tong}
                      onChange={this.handleChange_AtInputNumber.bind(this, 'tong')}
                      className="tongshu"
                    />
                    <AtInputNumber
                      min={0}
                      max={999}
                      step={0.1}
                      value={qianke}
                      onChange={this.handleChange_AtInputNumber.bind(this, 'qianke')}
                    /> 千克
                    </View>
                </View>
              </AtCard>

              <AtCard
                isFull={true}
                title='期望收集日期'
                thumb={riqi}
              >

                <View className='riqi'>
                  <Picker mode='date' onChange={this.onDateChange} start={this.state.dateSel}>
                    <View className='picker'>
                      当前选择：{this.state.dateSel}
                    </View>
                  </Picker>
                </View>

              </AtCard>

              <AtCard
                isFull={true}
                title='联系人&联系方式'
                thumb={lianxi}

              >
                <AtInput
                  error={!lianxiren}
                  name='lianxiren'
                  title='联系人'
                  type='text'
                  placeholder='请输入'
                  value={lianxiren}
                  onChange={this.handleChangeInput.bind(this, 'lianxiren')}
                />
                <AtInput
                  error={!shoujihao}
                  name='shoujihao'
                  title='手机号'
                  type='phone'
                  placeholder='请输入'
                  value={shoujihao}
                  onChange={this.handleChangeInput.bind(this, 'shoujihao')}
                />
              </AtCard>
              <AtButton loading={loading} type='primary' className='tijiao' onClick={this.onSubmit}>提交</AtButton>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={1} className='tan2Box'>
            <AtFloatLayout isOpened={isOpened} title="日期查询" onClose={this.ononClose} className='ribox'>
              <View className='chaxunBox'>查询时间 : {start} ~ {end} <AtButton className='chaxun' type='primary' size='small' full={true} circle={true} onClick={this.pagingQueryCollectorRecord}>查询</AtButton></View>
              <AtCalendar isMultiSelect onSelectDate={this.onSelectDate} />
            </AtFloatLayout>
            <View onClick={this.onisOpened} className='chaxunriq'>日期 <AtIcon value='chevron-down' size='20' color='#333'></AtIcon> </View>

            <View className="tab1" >
              {/* <View style='width:100%;height:20vh;background:#993;' >aaaaaaaa</View> */}
              <View className='dragUpdataPage'>
                <View className='downDragBox' style={downDragStyle}>
                  <AtActivityIndicator></AtActivityIndicator>
                  <Text className='downText'>{this.state.downText}</Text>
                </View>
                <ScrollView
                  style={dargStyle}
                  onTouchMove={this.touchmove}
                  onTouchEnd={this.touchEnd}
                  onTouchStart={this.touchStart}
                  onScrollToUpper={this.ScrollToUpper}
                  onScrollToLower={this.ScrollToLower}
                  className='dragUpdata'
                  scrollY={this.state.scrollY}
                  scrollWithAnimation>
                  <View style='width:100%;height:80vh;' >

                    <AtList>
                      {
                        ListData.map((item, index) => {
                          return (
                            <AtListItem
                              key={index}
                              title={item.hospitalName}
                              note={item.time + `  ` + item.bucketNum + `桶 ` + item.weight + `  kg`}
                            // extraText='详细信息'
                            // arrow='right'
                            // thumb={item.url}
                            onClick={this.onIndex.bind(this, item)}
                            />
                          )
                        })
                      }

                    </AtList>
                  </View>
                </ScrollView>
                <View className='upDragBox' style={upDragStyle}>
                  <AtActivityIndicator></AtActivityIndicator>
                  <Text className='downText'>{this.state.pullText}</Text>
                </View>
              </View>
            </View>
          </AtTabsPane>
        </AtTabs>
        <View style={{ height: '8vh' }}></View>
      </View>
    )
  }
}
